<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span v-if="pageType == 'apply'">学习填报</span>
        <span v-else>我的审核</span>
      </div>
    </template>

    <div class="search-form">
      <!-- 搜索区域 -->
      <el-form :inline="true" :model="formInline" class="demo-form-inline" ref="formInlineRef">
        <el-row>
          <!-- <el-form-item>
            <el-input v-model="formInline.studyUnitName" placeholder="请输入填报单位" clearable @keyup.enter="onSubmit"></el-input>
          </el-form-item> -->

          <el-form-item>
            <el-select v-model="formInline.studySubject" placeholder="请选择学习主题" clearable>
              <el-option v-for="(sItem, sIndex) in learnSubject" :key="sIndex" :label="sItem.name" :value="sItem.id" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-select v-model="formInline.studyWay" placeholder="请选择学习形式" style="width: 100%;" :teleported="false" clearable>
              <el-option label="集体学习讨论" value="1" />
              <el-option label="专题辅导报告" value="2" />
              <el-option label="现场调研" value="3" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-date-picker
              :teleported="false"
              v-model="formInline.studyDate"
              type="date"
              clearable
              style="width: 100%;"
              placeholder="请选择学习时间"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>

          <el-form-item>
            <el-select v-model="formInline.checkStatus" placeholder="请选择审核状态" style="width: 100%;" :teleported="false" clearable>
              <el-option label="待审核" value="0" />
              <el-option label="已初审" value="1" />
              <el-option label="已终审" value="2" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="onSubmit('search')">
              <el-icon>
                <Search />
              </el-icon>
            </el-button>
          </el-form-item>
        </el-row>
      </el-form>

      <!-- 新建 -->
      <div class="filter-depart">
        <el-button type="primary" @click="addFilling" v-if="isFilling && pageType == 'apply' && authStore.userInfo.orgId">新建</el-button>
      </div>

    </div>

    <div class="table-data" v-loading="loading">
      <el-table
        :data="fillingData"
        stripe
        borderresizable
        highlight-hover-row
        show-overflow
        keep-source
        scrollbar-always-on
      >
        <el-table-column
          v-for="(tableItem, tableIndex) in fillingTableColumns" :key="tableIndex"
          :prop="tableItem.field"
          :label="tableItem.label"
          :min-width="tableItem.minWidth"
          :formatter="tableItem.formatter"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          fixed="right"
          field="opera"
          label="操作"
          min-width="220"
        >
          <template #default="{ row }">
            <el-button
              type="warning"
              link
              @click="fillingDetail(row)"
            >查看</el-button>
            <el-button
              link
              @click="fillingEscalation(row)"
              v-if="row.checkStatus == -1 && isFilling && pageType == 'apply' && authStore.userInfo.orgId"
            >上报</el-button>
            <el-button
              type="warning"
              link
              @click="fillingApprove(row)"
              v-if="row.checkStatus != 2 && row.checkStatus != -1 && isFillingApproval && pageType == 'approval'"
            >审核</el-button>
            <el-button
              link
              v-if="row.checkStatus == -1"
            >审核未通过</el-button>
            <el-button
              link
              v-if="row.checkStatus == 2"
            >审核通过</el-button>
            <el-button
              type="success"
              link
              @click="fillingEdit(row)"
              v-if="(row.checkStatus == 0 || row.checkStatus == -1) && isFilling && pageType == 'apply' && authStore.userInfo.orgId"
            >编辑</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="table-page">
        <el-pagination background layout="prev, pager, next" :total="dataTotal" :page-size="pageSize" :current-page="currentPage" @current-change="currentChange" />
      </div>
    </div>

    <approval-dialog v-model:visible="dialogVisible" @approvalChange="approvalChange" :isNeedDes="true" />
  </el-card>
</template>

<script>
export default { name: 'backendLearnFilling' }
</script>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Search, Filter } from '@element-plus/icons-vue'
import { http } from '@/utils/http/index';
import { dateFormatter, checkStatusFormatter } from "@/utils/backend.js"
import approvalDialog from "@/components/backend/approval.vue"
import { useAuthStore } from '@/stores/modules/auth.js';
import { ContentTypeEnum } from '@/enums/httpEnum';

/* 路由 */
const router = useRouter()
const route = useRoute()

/* 用户信息 */
const authStore = useAuthStore()

/* 当前用户是否具备学习上报权限 */
const isFilling = computed(() => { 
  let actions = authStore.userInfo.actions
  if(!actions) return
  const find = actions.find(item => item.id == '2.1')
  return find ? true : false
})

/* 当前用户是否具备学习审核的权限 */
const isFillingApproval = computed(() => { 
  let actions = authStore.userInfo.actions
  if(!actions) return
  const find = actions.find(item => item.id == '3.1')
  return find ? true : false
})

/* 当前用户是否为最高级的系统管理员 */
const isFillingSystem = computed(() => {
  let actions = authStore.userInfo.actions
  if(!actions) return
  const find = actions.find(item => item.id == '4')
  return find ? true : false
})

const pageType = computed(() => {
  const current = route.path.replace(/\/backend/g, '')
  // 我的申请
  if (current == '/learn-filling') return 'apply'
  // 我的审核
  if (current == '/learn-filling-approval') return 'approval'
})

onMounted(() => {
  getLearnSubject()
  onSubmit()
})

watch(() => router.currentRoute.value.path, () => {
  formInline.value = {
    /* studyUnitName: "", */
    studySubject: "",
    studyWay: "",
    studyDate: "",
    checkStatus: "",
  }
  currentPage.value = 1
  onSubmit()
})

/* 左侧搜索表单 */
const formInlineRef = ref(null)
const formInline = ref({
  /* studyUnitName: "", */
  studySubject: "",
  studyWay: "",
  studyDate: "",
  checkStatus: "",
})

/* 学习主题下拉列表请求 */
const learnSubject = ref([])
const subjectPageIndex = ref(1)
const subjectPageSize = ref(200)

const getLearnSubject = () => {
  let params = {
    pageIndex: subjectPageIndex.value,
    pageSize: subjectPageSize.value
  }
  http.$POST(`/TheoryStudyM/GetTheoryStudySubjectLocalInfoList`, params).then(res => {
    learnSubject.value = learnSubject.value.concat(res.result.dataLst)
    if(res.result.countAll > res.result.pageIndex * res.result.pageSize){
      subjectPageIndex.value = subjectPageIndex.value + 1
      getLearnSubject()
    }
  }).catch(err => {
    ElMessage.warning("查询失败")
  })
}

/* 分页 */
const dataTotal = ref(0)
const pageSize = ref(20)
const currentPage = ref(1)

if(router.currentRoute.value.query.currentPage) {
  currentPage.value = Number(router.currentRoute.value.query.currentPage)
}

/* 切换页码方法 */
const currentChange = (val) => {
  currentPage.value = val
  onSubmit()
}

/* 表格数据加载动画 */
const loading = ref(false)

/* 表格数据 */
const fillingData = ref([])

/* 表格字段 */
const fillingTableColumns = reactive([
  { field: "studySubjectName", label: "学习主题", minWidth: "200" },
  { field: "studyUnit", label: "填报单位", minWidth: "200" },
  { field: "studyWay", label: "学习形式", minWidth: "120" },
  { field: "studyPersonNum", label: "学习人数", minWidth: "100" },
  { field: "studyHost", label: "主持人", minWidth: "120" },
  { field: "studySpeaker", label: "主讲人", minWidth: "140" },
  { field: "studyDate", label: "学习时间", minWidth: "170", formatter: dateFormatter },
  { field: "studySpokesman", label: "发言人", minWidth: "120" },
  { field: "studyPersons", label: "参加人员", minWidth: "170" },
  /* { field: "studyFileName", label: "学习文件", minWidth: "200" }, */
  { field: "checkStatus", label: "状态", minWidth: "120", formatter: checkStatusFormatter },
])

/* 点击搜索 */
const onSubmit = (type) => {
  loading.value = true
  let params = {
    pageIndex: currentPage.value,
    pageSize: pageSize.value
  }

  let dfi = {
    Logic: 0,
    Filters: [],
  }

  for(let k in formInline.value){
    if(formInline.value[k]){
      if(k == 'studySubject' || k == 'checkStatus') {
        dfi.Filters.push({
          Field: k,
          Operator: 8,
          value: formInline.value[k]
        })
      }else {
        dfi.Filters.push({
          Field: k,
          Operator: 0,
          value: formInline.value[k]
        })
      }
    }
  }

  if(pageType.value == 'apply') {
    dfi.Filters.push({
      Field: 'createuserid',
      Operator: 8,
      Value: authStore.userInfo.uid
    })
  }
  
  if(dfi.Filters.length){
    params.dfi = dfi
  }

  const url = pageType.value == 'apply' ? '/TheoryStudyM/GetTheoryStudyFillingInfoList' : '/TheoryStudyM/GetTheoryStudyFillingInfoList'

  http.$POST(url, params).then(res => {
    loading.value = false
    if (res.isError) return
    fillingData.value = res.result.dataLst
    dataTotal.value = res.result.countAll
  }).catch(err => {
    loading.value = false
    ElMessage.warning("查询失败，请重试")
  })
}

/* 点击新建 */
const addFilling = () => {
  http.$GET(`/PreachM/GetParentOrg_IsOrNo?authToken=${authStore.auth_token}`).then(res => {
    if(res == -1) return ElMessage({
      type: 'warning',
      message: '您当前账号暂未配置对应上级组织，无法进行填报，请联系管理员进行配置',
      duration: 2000
    })

    if(res == 2) return ElMessage({
      type: 'warning',
      message: '无用户信息，无法进行填报，请联系管理员进行配置',
      duration: 2000
    })

    if(res == 3) return ElMessage({
      type: 'warning',
      message: '您当前账号暂未配置相关组织，无法进行填报，请联系管理员进行配置',
      duration: 2000
    })
    router.push({
      path: "/backend/learn-filling/add",
      query: { type: 'add' }
    })
  })
}

/* 点击编辑 */
const fillingEdit = (row) => {
  http.$GET(`/PreachM/GetParentOrg_IsOrNo?authToken=${authStore.auth_token}`).then(res => {
    if(res == -1) return ElMessage({
      type: 'warning',
      message: '您当前账号暂未配置对应上级组织，无法进行填报，请联系管理员进行配置',
      duration: 2000
    })

    if(res == 2) return ElMessage({
      type: 'warning',
      message: '无用户信息，无法进行填报，请联系管理员进行配置',
      duration: 2000
    })

    if(res == 3) return ElMessage({
      type: 'warning',
      message: '您当前账号暂未配置相关组织，无法进行填报，请联系管理员进行配置',
      duration: 2000
    })
    router.push({
      path: "/backend/learn-filling/add",
      query: { id: row.id, type: 'edit', currentPage: currentPage.value }
    })
  })
}

/* 查看详情 */
const fillingDetail = (row) => {
  let { href } = router.resolve({
    path: "/backend/learn-filling/detail",
    query: { id: row.id, currentPage: currentPage.value }
  })
  window.open(href, "_blank")
}

/* 点击上报 */
const fillingEscalation = (row) => {
  let params = {
    id: row.id,
    checkStatus: 0
  }
  changeCheckStatus(params)
}

/* 审核弹窗 */
const dialogVisible = ref(false)

/* 当前列数据 */
const currentColumn = ref({})

/* 点击审核 */
const fillingApprove = (row) => {
  dialogVisible.value = true
  currentColumn.value = row
}

/* 提交审核回调 */
const approvalChange = (approvalForm) => {
  console.log(approvalForm.approvalDec);
  console.log(approvalForm.approval);
  let params = {}
  if(approvalForm.approval == '1') {
    params = {
      id: currentColumn.value.id,
      checkStatus: currentColumn.value.checkStatus + 1
    }
  }else {
    params = {
      id: currentColumn.value.id,
      checkStatus: -1
    }
  }
  changeCheckStatus(params)
}

/* 更改状态值 */
const changeCheckStatus = (params) => {

  http.$POST("/TheoryStudyM/AddOrUpdateTheoryStudyFilling", {...params}, { headers: { 'Content-Type': ContentTypeEnum.FORM_DATA } }).then(res => {
    if (res.IsError) {
      ElMessage.warning(res.Message);
    }else{
      ElMessage.success('操作成功');
      onSubmit()
    }
  }).catch(err => {
    ElMessage.warning('操作失败');
  })
}
</script>

<style lang='scss' scoped>
@import "@/assets/styles/backendElement.scss";
.filter-button{
  :deep(.el-form-item__content){
    justify-content: center;
  }
}
</style>